package cn.gzsxt.service.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import cn.gzsxt.mapper.ModularMapper;
import cn.gzsxt.mapper.PermissionMapper;
import cn.gzsxt.service.ModularService;
import cn.gzsxt.utils.Page;

@Service
public class ModularServiceImpl implements ModularService {
	private static final Logger LOGGER=LogManager.getLogger(ModularServiceImpl.class);
	
	@Autowired
	private ModularMapper modularMapper;
	
	@Autowired
	private PermissionMapper permissionMapper;

	@Override
	public Map<String, Object> addModular(Map<String, Object> modular) {
		int count = modularMapper.insert(modular);
		if(count>0){
			return modular;
		}
		return null;
	}

	@Override
	public int deleteModularByIds(Object... modularIds) {
		return modularMapper.deleteByIds(modularIds);
	}

	@Override
	public Map<String, Object> editModular(Map<String, Object> modular) {
		int count = modularMapper.updateForNotnull(modular);
		if (count>0) {
			return modular;
		}
		return null;
	}

	@Override
	public List<Map<String, Object>> findAllModular() {
		return modularMapper.findAll();
	}

	@Override
	public List<Map<String, Object>> findAllModularIncPermission() {
		List<Map<String, Object>> modulars = modularMapper.findAll();
		//将模块对应的权限加上到模块对象里面
		for (Map<String, Object> modular : modulars) {
			//通过模块编号查询权限
			Object modularId = modular.get("MODULAR_ID");
			Map<String, Object> condition=new HashMap<String, Object>();
			condition.put("MODULAR_ID", modularId);
			//通过模块编号查询权限
			List<Map<String, Object>> permissions = permissionMapper.findByCondition(condition);
			//将权限数据放在模块里面
			if (permissions!=null) {
				modular.put("permissions", permissions);
			}
			
		}
		LOGGER.debug("ModularServiceImpl.findAllModularIncPermission.模块数据："+modulars);
		return modulars;
	}

	@Override
	public Page findModularByConditionToPage(Map<String, Object> condition, int index, int size) {
		//构建一个分页对象
		//1.获得总记录数据
		long count = modularMapper.count(condition);
		//2.获得分页数据
		int start=index*size;
		List<Map<String, Object>> moduarls = modularMapper.findByConditionAndPage(condition, start, size);
		//3.构建分页对象
		Page page=new Page(index, size, count, moduarls);
		//4.返回分页对象
		return page;
	}

	@Override
	public Map<String, Object> findModularById(Object modularId) {
		
		return modularMapper.findById(modularId);
	}

}
